<template>
  <div class="evaluation-page">
    <h2>评测任务管理</h2>
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    <div v-if="isLoading" class="loading-indicator">
      加载中...
    </div>
    <div class="current-version">
      当前版本: {{ versionStore.currentVersion?.ver_code || '未选择' }}
    </div>
    
    <div class="task-list">
      <h3>评测任务列表</h3>
      <div v-if="tasks.length === 0" class="empty-tips">
        暂无评测任务，使用侧边栏工具进行创建。
      </div>
      <div v-else>
        <div v-for="task in tasks" :key="task.id" class="task-item">
            <div class="task-basic-info" @click="handleTaskClick(task)">
              <div class="task-id-name">
                <span class="task-id">ID: {{ task.id }}</span>
                <span class="task-name">{{ task.title }}</span>
              </div>
              <div class="task-meta">
                <span :class="['status-badge', 'status-' + task.status.toLowerCase()]">
                  {{ task.status }}
                </span>
                <span class="task-time">创建于: {{ task.time }}</span>
                <button 
                  v-if="task.status === 'PENDING'"
                  @click.stop="handleRunTask(task.id)"
                  class="run-btn"
                >
                  执行
                </button>
                <button 
                  v-else
                  class="run-btn disabled"
                  disabled
                >
                  {{ task.status === 'RUNNING' ? '运行中...' : '已完成' }}
                </button>
              </div>
            </div>
          
          <!-- 任务详情区域 -->
          <div v-if="selectedTask?.id === task.id" class="task-details">
            <h4>任务配置</h4>
            <p><strong>标题:</strong> {{ task.title }}</p>
            <p><strong>描述:</strong> {{ task.description }}</p>
            <p><strong>提示:</strong> {{ task.prompt }}</p>
            <p><strong>裁判模型:</strong> {{ task.judges.join(', ') }}</p>
            <p><strong>评测对象:</strong> {{ task.models.join(', ') }}</p>
            
            <!-- 完成的任务显示表格 -->
            <div v-if="task.status === 'COMPLETED'" class="task-results">
              <h4>评测结果</h4>
              <table class="result-table">
                <thead>
                  <tr>
                    <th>问题ID</th>
                    <th>问题内容</th>
                    <th>模型</th>
                    <th>模型回答</th>
                    <th>评测报告</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="answer in taskAnswers" :key="answer.id">
                    <td>{{ answer.question.id }}</td>
                    <td class="content-cell" @click.stop="showFullContent(answer.question.question, '问题内容')">
                      {{ truncateContent(answer.question.question) }}
                    </td>
                    <td>{{ answer.model }}</td>
                    <td class="content-cell" @click.stop="showFullContent(answer.answer, '模型回答')">
                      {{ truncateContent(answer.answer) }}
                    </td>
                    <td class="content-cell" @click.stop="showFullContent(answer.evaluation || '暂无评测报告', '评测报告')">
                      {{ truncateContent(answer.evaluation || '暂无评测报告') }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建评测任务功能已移至侧边栏和标准问题管理页面 -->
    
    <!-- 添加模态框组件 -->
    <div v-if="showModal" class="modal-overlay" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <pre>{{ modalContent }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useVersionStore } from '@/stores/versionStore'
import { 
  runTask,
  getTasks,
  type GetTasksResponse,
  getTaskAnswers,
  type LlmAnswerResponse,
  getAnswerEvaluates,
} from '@/api/evaluation.ts'

// 将接口定义移到 setup 之外，避免私有类型错误
interface AnswerWithEvaluation extends LlmAnswerResponse {
  evaluation: string
}

export default defineComponent({
  name: 'EvaluationPage',
  setup() {
    const versionStore = useVersionStore()
    const tasks = ref<GetTasksResponse[]>([])
    const availableJudges = ref(['gpt-4', 'claude-2', 'llama-2'])
    const availableModels = ref(['gpt-3.5', 'claude-instant', 'llama-7b'])

    const formatDate = (dateStr: string) => {
      return new Date(dateStr).toLocaleString()
    }

    const isLoading = ref(false)
    const errorMessage = ref('')
    
    // 创建评测任务逻辑已移至全局状态管理

    const selectedTask = ref<GetTasksResponse | null>(null)
    const taskAnswers = ref<AnswerWithEvaluation[]>([])
    const showModal = ref(false)
    const modalTitle = ref('')
    const modalContent = ref('')
    
    const truncateContent = (content: string | null | undefined, length = 50) => {
      if (!content) return ''
      return content.length > length ? content.substring(0, length) + '...' : content
    }

    const showFullContent = (content: string | null | undefined, title: string) => {
      modalTitle.value = title
      modalContent.value = content || '无内容'
      showModal.value = true
    }

    const closeModal = () => {
      showModal.value = false
    }

    const handleTaskClick = async (task: GetTasksResponse) => {
      // 直接切换选中状态
      selectedTask.value = selectedTask.value?.id === task.id ? null : task
      
      // 如果是选中状态且任务已完成，则加载回答和评测报告
      if (selectedTask.value?.id === task.id && task.status === 'COMPLETED') {
        isLoading.value = true
        try {
          const answers = await getTaskAnswers(task.id)
          // 为每个回答获取评测报告
          taskAnswers.value = await Promise.all(answers.map(async answer => {
            const evaluates = await getAnswerEvaluates(answer.id)
            // 合并评测报告，如果有多个评测，用换行符连接
            const evaluation = evaluates.map(e => 
              `[裁判模型: ${e.judge}]\n${e.singleReport}`
            ).join('\n\n')
            return {
              ...answer,
              evaluation
            } as AnswerWithEvaluation
          }))
        } catch (error) {
          errorMessage.value = '获取任务数据失败: ' + (error as Error).message
          console.error('获取任务数据失败:', error)
        } finally {
          isLoading.value = false
        }
      }
    }

    const handleRunTask = async (taskId: number) => {
      isLoading.value = true
      errorMessage.value = ''
      try {
        await runTask(taskId)
        await fetchTasks()
      } catch (error) {
        errorMessage.value = '执行评测任务失败: '+ (error as Error).message
        console.error('执行评测任务失败:', error) 
      } finally {
        isLoading.value = false
      }
    }

    const fetchTasks = async () => {
      if (!versionStore.currentVersion?.ver_code) {
        errorMessage.value = '请先选择版本'
        return
      }
      
      isLoading.value = true
      errorMessage.value = ''
      try {
        const versionCode = versionStore.currentVersion.ver_code
        console.log(`正在获取版本 ${versionCode} 的评测任务...`)
        tasks.value = await getTasks(versionCode)
        console.log('获取到的任务列表:', tasks.value)
      } catch (error) {
        errorMessage.value = '获取任务列表失败: ' + (error as Error).message
        console.error('获取任务列表失败:', error)
      } finally {
        isLoading.value = false
      }
    }

    // 初始化加载任务列表
    fetchTasks()

    return {
      versionStore,
      tasks,
      availableJudges,
      availableModels,
      formatDate,
      handleTaskClick,
      handleRunTask,
      fetchTasks,
      isLoading,
      errorMessage,
      selectedTask,
      taskAnswers,
      showModal,
      modalTitle,
      modalContent,
      truncateContent,
      showFullContent,
      closeModal
    }
  }
})
</script>

<style scoped>
.evaluation-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.current-version {
  margin: 10px 0 20px;
  font-size: 16px;
  color: #666;
}

.task-list {
  margin: 20px 0;
}

.task-item {
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  transition: all 0.2s ease;
}

.task-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.task-item.status-running {
  border-left: 4px solid #007bff;
}

.task-item.status-completed {
  border-left: 4px solid #28a745;
}

.task-basic-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  cursor: pointer;
}

.task-id-name {
  display: flex;
  align-items: center;
  gap: 16px;
}

.task-id {
  font-family: monospace;
  color: #666;
}

.task-name {
  font-weight: bold;
}

.task-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-meta {
  color: #666;
  font-size: 14px;
  margin-left: 10px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeeba;
}

.status-running {
  background-color: #cce5ff;
  color: #004085;
  border: 1px solid #b8daff;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.status-failed {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.run-btn.disabled {
  background-color: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
}

.error-message {
  color: red;
  margin: 10px 0;
  padding: 10px;
  background-color: #ffeeee;
  border-radius: 4px;
}

.loading-indicator {
  margin: 10px 0;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.run-btn {
  margin-left: 10px;
  padding: 4px 8px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.task-details {
  margin-top: 15px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.task-answers {
  margin-top: 20px;
}

.result-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.result-table th,
.result-table td {
  padding: 12px;
  border: 1px solid #ddd;
  text-align: left;
}

.result-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.content-cell {
  cursor: pointer;
  color: #2196F3;
}

.content-cell:hover {
  text-decoration: underline;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  overflow: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body {
  padding: 16px;
}

.modal-body pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.run-btn:hover {
  background-color: #0b7dda;
}

/* 创建评测任务相关样式已移除 */
</style>
